package org.apogeescience.connector;

import java.io.IOException;

import org.apogeescience.config.DatabaseConfiguration;

public class DatabaseConnector {
	private static final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
    
    private String url;
    private String driver;
    
    /**
     * Constuctor of the database connector
     * @param dbConfig database configuration to load
     * @throws IOException
     */
    public DatabaseConnector(DatabaseConfiguration dbConfig) throws IOException {
    	configureDatabase(dbConfig);
    }

	private void configureDatabase(DatabaseConfiguration dbConfig) throws IOException {		
		String serverAddress = dbConfig.getDatabaseAddress();
		int port = dbConfig.getDatabasePort();
		String dbName = dbConfig.getDatabaseName();
		
		DatabaseType type = DatabaseType.valueOf(dbConfig.getDatabaseType());
		
		switch (type) {
		case MYSQL:
			this.url = String.format("jdbc:mysql://%s:%d/%s", serverAddress, port, dbName);
			this.driver = dbConfig.getDatabaseDriver() != null ? dbConfig.getDatabaseName() :MYSQL_DRIVER;
			break;
		case ORACLE:
			this.url = String.format("jdbc:oracle:thin:@%s:%d:%s", serverAddress, port, dbName);
			this.driver = dbConfig.getDatabaseDriver() != null ? dbConfig.getDatabaseName() :ORACLE_DRIVER;
			break;
		case SQLSERVER:
			break;
		default:
			break;
		}	
	}
	
	/**
	 * Gets the jdbc driver to use
	 * @return
	 */
	public String getDriver() {
		return this.driver;
	}
	
	/**
	 * Gets the database connection string
	 * @return
	 */
	public String getConnection() {
		return this.url;
	}
}
